// dojo.provide("apt.PlanningToolBootstrap");
dojo.provide("apt.PlanningTool");
dojo.require("apt.ResourceList");
dojo.require("apt.CalendarComponent");
dojo.require("apt.FilterPopover");
dojo.require("dojo.store.Cache");
dojo.require("dojo.store.Memory");
dojo.require("dojo.store.JsonRest");
dojo.require("dijit._WidgetBase");
dojo.require("dijit._TemplatedMixin");


dojo.declare("apt.PlanningTool", [dijit._WidgetBase, dijit._TemplatedMixin], {
    templateString: dojo.cache('apt.templates', 'PlanningTool.html'),
    widgetsInTemplate: true,
    // today: new Date(),
    // referenceDate: new Date(),
    // isLogged: '',
    subWidgets: {
        calendarComponentWidget: {},
        resourceWidgets: {},
        dataWidget: {}
    },
    stores: {},
    resizeTimeout: "",
    settings: {},
    daysShowing: 21,
    resources: [],
    filters: [], today: '',
    variables: {break: "T", work: "P"}, //work: "P"
    dimensions: {sidebarWidth: 180},

    constructor: function (data) {
        this.inherited(arguments);

        //Combine default calendarData with those provided by arguments
        dojo.safeMixin(this, data);

        var self = this;
        var now = new Date().setHours(0, 0, 0, 0);
        // Generate resources from availability data, becouse we have no other source at this point.
        this.today = new Date(now); //new Date("2014", "8", "9", "12", "00", "00", "00"); //new Date(now); //new Date("2012", "5", "11", "12", "00", "00", "00"); //2014-09-09
        // console.log(this.today);
        // debugger;
        // var memoryStore = new dojo.store.Memory({});
        this.stores.resx = new dojo.store.JsonRest({target: "Service/Resources.aspx"});
        this.stores.availabilities = new dojo.store.JsonRest({target: "Service/Calendar.aspx"});
        this.stores.reservations = new dojo.store.JsonRest({target: "Service/ReservationTimeServices.aspx"});
        this.stores.resources = new dojo.store.Memory({data: storedata.resources, idProperty: "SmanId"});
        this.stores.shifts = new dojo.store.Memory({data: storedata.shifts, idProperty: "ShiftId"});
        this.stores.departments = new dojo.store.Memory({data: storedata.departments, idProperty: "Code"});
    },

    postCreate: function () {
        var filterObj = dojo.queryToObject(window.location.search.replace("?", ""));
        this.daysShowing = filterObj.daysShowing || 7;
        this.filterByResourceId = filterObj.smanid;
        this._createSubwidgets();

        dojo.connect(window, "onresize", this, "delayedResize");
        document.pt = this;

        //this.resizeSubWidgets();

        dojo.query(".viewbtn.active").removeClass("active");
        dojo.query(".daysShowing" + this.daysShowing).addClass("active");


        this.resizeSubWidgets();

        dojo.query("#ptloading").orphan();

        dojo.connect(this.filterPoint, 'onclick', this, this.toggleFilters);
        dojo.connect(this.document, "onclick", this, this.clickHandler);
    },

    clickHandler: function (event) {
        //console.log('click !');
        if (dojo.hasClass(event.target, 'reservation') || dojo.hasClass(event.target.parentNode, 'reservation')) {
            var target;
            if (dojo.hasClass(event.target, 'reservation')) {
                target = event.target;
            } else if (dojo.hasClass(event.target.parentNode, 'reservation')) {
                target = event.target.parentNode;
            }

            if (typeof target !== 'undefined') {
                dijit.byNode(target).showInfo();
            }
        }
        if (dojo.hasClass(event.target, 'btn')) {
            var parent = event.target.parentNode;
            var target = event.target;
            var value = dojo.attr(target, 'data-pt');

            if (dojo.hasClass(target, 'viewbtn') && typeof value != 'undefined' && value > 0) {
                dojo.query('.active', parent).removeClass('active');
                dojo.addClass(target, 'active');
                this.changeDaysShowingCustom(value);
            } else if (dojo.hasClass(target, 'movebtn') && typeof value != 'undefined') {
                this.moveCalendar(value);
            }
        }
    },

    moveCalendar: function (value) {
        this.subWidgets.calendarComponentWidget.regenerateDays(value);
    },

    addResource: function (id) {
        var match = false;
        dojo.forEach(this.resources, function (e, i) {
            if (e.SmanId == id) {
                e.count++;
                match = true;
            }
        });

        if (!match) {
            this.resources.push({SmanId: id, count: 1});
            this.renderResourceList();
        }
    },

    removeResource: function (id) {
        var match = false;
        var t = this;
        dojo.forEach(this.resources, function (e, i) {
            if (typeof e !== 'undefined' && e.hasOwnProperty('SmanId') && e.SmanId == id) {
                e.count--;
                if (e.count < 1) {
                    match = i;
                }
            }
        });
        if (match !== false) {
            t.resources.splice(match, 1);
            dojo.query('.datarow-' + id).orphan();
            t.renderResourceList();
        }
    },

    toggleFilters: function (e) {
        dojo.stopEvent(e);
        if (typeof this.filter !== "object") {
            this.filter = new apt.FilterPopover({parent: this});
        }
        this.filter.show();
        // console.log('toimii');
    },

    changeDaysShowingOne: function (event) {
        dojo.query('.btn.active').removeClass('active');
        dojo.addClass(event.target, 'active');

        this.changeDaysShowingCustom(1);
    },

    changeDaysShowingWeek: function (event) {
        dojo.query('.btn.active').removeClass('active');
        dojo.addClass(event.target, 'active');

        this.changeDaysShowingCustom(7);
    },

    changeDaysShowingFive: function (event) {
        dojo.query('.btn.active').removeClass('active');
        dojo.addClass(event.target, 'active');

        this.changeDaysShowingCustom(5);
    },

    changeDaysShowingCustom: function (days) {
        this.daysShowing = days;
        this.resizeSubWidgets();
    },

    delayedResize: function () {
        //Debounce resizing by delaying it for 300ms to save cpu cycles.
        clearTimeout(this.resizeTimeout);
        this.resizeTimeout = setTimeout(dojo.hitch(this, "resizeSubWidgets"), 300);
    },

    _createSubwidgets: function () {
        //debugger;
        //console.log(this.today);
        this.subWidgets.calendarComponentWidget = new apt.CalendarComponent({
            startDate: this.today, // new Date("2012", "5", "11", "12", "00", "00", "00"),
            parent: this
        });
        this.subWidgets.calendarComponentWidget.placeAt(this.calendarComponentContainer);
        this.subWidgets.calendarComponentWidget.startup();

        this.resizeSubWidgets();
    },

    _showFilters: function () {
    },

    resize: function () {
        this.resizeSubWidgets();
    },

    resizeSubWidgets: function () {

        dojo.style(this.sidebarNode, 'width', this.dimensions.sidebarWidth + "px");
        var contentWidth = dojo.position(this.domNode).w - this.dimensions.sidebarWidth;

        dojo.style(this.calendarComponentContainer, 'width', contentWidth + "px");

        this.subWidgets.calendarComponentWidget.resize();
    },

    renderResourceList: function () {
        var name = null;

        this.subWidgets.resourceWidgets = this.subWidgets.resourceWidgets || [];
        dojo.query('.resourceWidget').orphan();
        //debugger;
        // isFiltered ?
        var resources = this.resources || {};
        if (this.filterByResourceId && this.filterByResourceId  != 0) {
            resources = [{
                SmanId: this.filterByResourceId,
                count: 1
            }];
        }
        for (var i = 0; i < resources.length; i++) {
            if (resources[i].count > 0) {
                var resourceInfo = this.stores.resources.get(resources[i]['SmanId']);
                if (typeof resourceInfo != 'undefined' && resourceInfo.hasOwnProperty('Name') && resourceInfo.Name.length > 0) {
                    name = resourceInfo['Name'];
                } else {
                    name = resources[i]['SmanId'] || 'undefined';
                }
                //debugger;
                this.subWidgets.resourceWidgets[i] = new apt.ResourceList({name: name});
                this.subWidgets.resourceWidgets[i].placeAt(dojo.byId('resourceList'));
            }
        }
        ;
        this.subWidgets.calendarComponentWidget.resizeCalendarComponentHeight();
    }

});

